package com.bjpowernode.servlet;

import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.PrintWriter;
import java.sql.*;
public class StudentServlet implements Servlet {

    public void init(ServletConfig config) throws ServletException {

    }

    public void service(ServletRequest req, ServletResponse res)
            throws ServletException, IOException {
            //编写JDBC代码，链接数据库。查询所有学生信息
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            //注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //获取连接
            String url = "jdbc:mysql://localhost:3306/bjpowernode";
            String user = "root";
            String password = "CYHcyh123";
            conn = DriverManager.getConnection(url, user, password);
            //获取预编译的数据库操作对象
            String sql = "select no,name from t_student";
            ps =conn.prepareStatement(sql);
            //执行SQL
            rs = ps.executeQuery();
            //处理查询结果集
            while (rs.next()){
                String no = rs.getString("no");
                String name = rs.getString("name");
                System.out.println(no+" "+name);
            }

        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //释放资源
            if(rs!=null){
                try {
                    rs.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
            if(ps!=null){
                try {
                    ps.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
            if(conn!=null){
                try {
                    conn.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }

    }
}



    public void destroy() {

    }


    public String getServletInfo() {
        return "My First Servlet";
    }


    public ServletConfig getServletConfig() {
        return null;
    }
}